package com.luhuiguo.cms.server.web;

import java.io.IOException;
import java.io.Writer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.appengine.api.datastore.Blob;
import com.luhuiguo.cms.server.entity.Attachment;
import com.luhuiguo.cms.server.service.AttachmentService;

@Controller
public class UploadController {

    @Autowired
    private AttachmentService attachmentService;

    @RequestMapping(value = "/*/upload", method = RequestMethod.POST)
    public void handleUpload(@RequestParam("articleId") Long articleId, @RequestParam("file") MultipartFile file,
            @RequestParam("title") String title, @RequestParam(value = "rank", defaultValue = "0") int rank,
            @RequestParam(value = "grade", defaultValue = "0") int grade,
            @RequestParam(value = "description", required = false) String description, Writer writer) {
        String result = "failure";

        try {
            Attachment a = new Attachment();

            a.setArticleId(articleId);
            a.setTitle(title);
            a.setRank(rank);
            a.setGrade(grade);

            a.setFilename(file.getOriginalFilename());
            a.setMimeType(file.getContentType());
            a.setSize(file.getBytes().length);
            a.setContent(new Blob(file.getBytes()));
            a.setDescription(description);
            attachmentService.saveAttachment(a);

            result = "success";

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            writer.write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
